package service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import entity.Area;
import entity.Category;
import entity.Movie;
import entity.MoviePage;
import mapper.AreaMapper;
import mapper.CategoryMapper;
import mapper.MiddleMapper;
import mapper.MovieMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

import java.util.List;

@Service
public class MovieServiceImpl implements MovieService {
    @Autowired
    private MovieMapper movieMapper;

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private AreaMapper areaMapper;

    @Autowired
    private MiddleMapper middleMapper;

    @Override
    public MoviePage getAllMovies(List<Integer> categoryIds, Integer pageNum, Integer pageSize) {
        //设置页码和页面大小
        PageHelper.startPage(pageNum,pageSize);

        //查询，查询语句被pagehelper拦截
        List<Movie> movies = movieMapper.selectAllMovies(categoryIds);

        //分页
        PageInfo<Movie> info = new PageInfo<>(movies);

        //转换
        MoviePage moviePage = new MoviePage();
        moviePage.setMovieList(info.getList());
        moviePage.setPageCount(info.getPages());
        moviePage.setRowCount((int) info.getTotal());
        moviePage.setPageNum(pageNum);
        moviePage.setPageSize(pageSize);

        return moviePage;
    }

    @Override
    public List<Category> getAllCategories() {
        return categoryMapper.selectAllCategories();
    }

    @Override
    public List<Area> getAllAreas() {
        return areaMapper.selectAllAreas();
    }

    @Override
    public Integer addOneMovie(Movie movie, List<Integer> categories) {
        if (movieMapper.insertOneMovie(movie) == 0){
            return 0;
        }
        middleMapper.insertMovieCategories(movie.getId(), categories);
        return 1;
    }

    @Override
    public Movie getMovieById(Integer id) {
        return movieMapper.selectMovieById(id);
    }

    @Override
    public Category getCategoryById(Integer categoryId) {
        return categoryMapper.selectCategoryById(categoryId);
    }

    @Override
    public Integer setOneMovie(Movie movie, List<Integer> categories) {

        if(movieMapper.updateOneMovie(movie) == 0){
            return 0;
        }

        List<Integer> list = new ArrayList<>();
        list.add(movie.getId());
        //从中间表删除所有分类
        middleMapper.deleteCategoriesByMovieList(list);

        //插入分类中间表
        middleMapper.insertMovieCategories(movie.getId(), categories);
        return 1;
    }

    @Override
    public Integer delMovieByList(List<Integer> movieList) {
        middleMapper.deleteCategoriesByMovieList(movieList);
        movieMapper.deleteMovieByList(movieList);
        return 1;
    }
}
